<?php
use com\gdl\common\dataobject\common\ResultDO; 
use com\gdl\kq\interfaces\AttAppUserServiceIf;
use com\gdl\kq\dataobject\user\UserLoginDTO; 
use com\gdl\kq\dataobject\user\UserSendSmsDTO; 
use com\gdl\kq\dataobject\user\UserPhoneLogin; 
use com\gdl\kq\dataobject\user\UserDTO; 
 
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use MagicCrypt\MagicCrypt;
/**
 * 考勤系统App用户相关
 */
class api_AttAppUserService extends api_Abstract implements AttAppUserServiceIf{
	
	# 默认留底照片
	static public $photo = "";
	
	//App用户名手机号码登录
	public function userLogin(UserLoginDTO $user){
		#接受参数
		$username = $user->username ? gdl_lib_BaseUtils::getStr($user->username) : "";
		$password = $user->password ? gdl_lib_BaseUtils::getStr($user->password) : "";
		$type = $user->type ? gdl_lib_BaseUtils::getStr($user->type) : "";
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		try{
			$userModel = new model_attendance_member();
			$processService = new service_appprocess();# 获取审批流程规则
			$condition[$type] = $username;
			$condition['status'] = 2;
			$userFiled = "*";
			$user = $userModel->selectOne($condition, $userFiled);
			$platformId = $user['platformId']?$user['platformId']:0;
			$userId = $user['id']?$user['id']:0;
			
			#判断如果是手机号要判断是否绑定手机号
			if($type=='phone'){
				if($user['isBind']!=1){$result->message = "该手机号未绑定"; return $result;}
			}
			
			if($user['id']){
				$randPassword = md5((gdl_lib_BaseUtils::IsMd5($password) ? md5($password) : md5(md5($password))) . $user['passsalt']);
				
				 if($user['password']==$randPassword){
					 #修改操作 登录成功新增用户token和过期时间
					 $token = parent::random(32); 
					 $tokenTimeOut = time()+7200; 
					 $updateUser = ['lastLoginTime'=>time(), 'token'=>$token, 'tokenTimeOut'=>$tokenTimeOut, 'isFirstLogin'=>2]; # isFirstLogin 1:第一次登陆 2：正常
					 $upWhere['id'] = $user['id'];
					 $addToken = $userModel->update($upWhere, $updateUser);
					 
					 #部门
					 $unitsModel = new model_lhbase_units();
					 $departmentId = isset($user['unitId'])?$user['unitId']:$user['departmentId'];
					 $unitsWhere = "id={$departmentId}";
					 $departmentName = $unitsModel->selectOne($unitsWhere, "id,unitName");
					 $departmentName = isset($departmentName['unitName'])?$departmentName['unitName']:"无部门";
					 
					 #职位
					 $positionModel = new model_attendance_position();
					 $positionId = isset($user['positionId'])?$user['positionId']:0;
					 $positionWhere = "id ={$positionId}";
					 $positionName = $positionModel->selectOne($positionWhere, "id,title");
					 $positionName = isset($positionName['title'])?$positionName['title']:"无职位";
					 
					 #性别
					 $sex = $this->checkSex($user['idcard']);
					 if(empty($user['idcard'])){$sex = 0;}
					 
					#考情组
					$kqModel = new model_attendance_attendancegroup();
					$leftJoin = [
						'atd_attendance_group_user as kquser' => 'atd_attendance_group.id=kquser.agId',
					];
					$kqFiled = "kquser.id,atd_attendance_group.id, atd_attendance_group.title";
					$kqWhere = "kquser.memberId={$user['id']} and atd_attendance_group.isdelete=0";
					$proInfo = $kqModel->selectOne($kqWhere,$kqFiled,'','',$leftJoin);
					$kqId = $proInfo['id']?$proInfo['id']:"0";
					$kqName = $proInfo['title']?$proInfo['title']:"无考勤组";
					
					#查请假流程
					$leave = 1; #1：有审批流程 2：没有
					$processResult = $processService->getMemberProcess($userId, $platformId, 1); #1:请假 2：外出 3：补卡 
					$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
					if(empty($recomdRule)){$leave = 2;}
					#外出流程
					$outgo = 1; #1：有审批流程 2：没有
					$processResult = $processService->getMemberProcess($userId, $platformId, 2); #1:请假 2：外出 3：补卡 
					$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
					if(empty($recomdRule)){$outgo = 2;}
					#补卡流程
					$recard = 1; #1：有审批流程 2：没有
					$processResult = $processService->getMemberProcess($userId, $platformId, 3); #1:请假 2：外出 3：补卡 
					$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
					if(empty($recomdRule)){$recard = 2;}
					 
					 if($addToken){
						#返回数据
						$photo = $user['photo']?$user['photo']:self::$photo;
						$resultData['userInfo'] = json_encode(['userId'=>$user['id'],'leave'=>$leave,'outgo'=>$outgo,'recard'=>$recard,'proGroupName'=>$kqName,'proGroupId'=>$kqId,'sex'=>$sex, 'isFirstLogin'=>$user['isFirstLogin'], 'departmentName'=>$departmentName, 'positionName'=>$positionName,'jobnumber'=>$user['jobNumber'], 'photo'=>$photo, 'photoStatus'=>$user['photoStatus'], 'platformId'=>$user['platformId'], 'unitId'=>$user['unitId'], 'userName'=>$user['userName'], 'realName'=>$user['realName'], 'idcard'=>$user['idcard'], 'phone'=>$user['phone'],'isBindPhone'=>$user['isBind'],'isCharge'=>$user['isCharge'],'token'=>$token]);
						$result->data[] = $resultData;
						$result->code = 200;
						$result->message = "登录成功";
					 }else{
						 $result->message = "token更新失败";
					 }
					 
				 }else{
					 $result->message = "密码错误";
				 }
			}else{
				$result->message = "用户不存在";
				if($type=='phone'){$result->message = "未绑定手机号";}
			}
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		 
        return $result; 
	}
	
    //App发送短信
	// type类型为发送短信的类型
	// [type:login]登录短信 [type:bing]绑定短信 [type:reg]注册短信  ['isBing']验证绑定手机   [type:repassword]修改密码 [type:retrieve]忘记密码or找回密码
	public function sendSms(UserSendSmsDTO $user){
		# 接受参数
		$phone = $user->phone ? gdl_lib_BaseUtils::getStr($user->phone) : "";
		$type = $user->type ? gdl_lib_BaseUtils::getStr($user->type) : "";
		$userId = $user->userid ? gdl_lib_BaseUtils::getStr($user->userid) : ""; #绑定手机号需要用 #修改密码 # 修改手机号需要
		
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($phone)){ $result->message = "请填写手机号码"; return $result;}
		
		try{
			$verifyModel = new model_attendance_verifycode();
			$userModel = new model_attendance_member();
			#生成验证码
			$code = mt_rand(100000,999999);
			$insertData['code'] = $code;
			$insertData['phone'] = $phone;
			$insertData['expireTime'] = time()+7200; #实际上定义为两个小时
            $insertData['createTime'] = time();
			$insertData['status'] = 1;
			
			switch ($type){
				case 'login':
					$strCode = "【安管控】您正在登录该账号，验证码：".$code.",有效期5分钟";
					$where = "phone = {$phone} and status =2 ";
					$emptyUserId = $userModel->selectOne($where, "id");
					if(empty($emptyUserId)){$result->message = "该手机号未绑定"; return $result;}
					$insertData['userId'] = $emptyUserId['id'];
					$result->data[] = ['userId'=>$emptyUserId['id'],'phone'=>$phone];
				break;  
				  
				case 'bing':
					$strCode = "【安管控】您正在绑定手机号，验证码：".$code.",有效期5分钟";
					if(empty($userId)){$result->message = "缺少UserID"; return $result;}
					$where = "phone = {$phone} and status =2 ";
					$emptyUserId = $userModel->selectOne($where, "id,phone,isBind");
					if($emptyUserId['phone'] && $emptyUserId['isBind']==1){$result->message = "该手机号已被注册，请勿重复绑定"; return $result;}
					$insertData['userId'] = $userId;
					$result->data[] = ['userId'=>$userId,'phone'=>$phone];
				 break;
				  
			    case 'reg':
					$strCode = "【安管控】您正在注册账号，验证码：".$code.",有效期5分钟";
					$where = "phone = {$phone} and status =2 ";
					$emptyUserId = $userModel->selectOne($where, "id,phone,isBind");
					if($emptyUserId['phone'] && $emptyUserId['isBind']==1){$result->message = "该手机号已被注册"; return $result;}
					$insertData['userId'] = 0;
					$result->data[] = ['userId'=>0,'phone'=>$phone];
			    break;
				
				case 'repassword':
					$strCode = "【安管控】您正在重置密码，验证码：".$code.",有效期5分钟";
					$where = "phone = {$phone} and status =2 ";
					$emptyUserId = $userModel->selectOne($where, "id,phone,isBind");
					if($emptyUserId['phone'] && $emptyUserId['isBind']==1){
						$insertData['userId'] = $emptyUserId['id'];
						$result->data[] = ['userId'=>$emptyUserId['id'],'phone'=>$phone];
					}else{
						$result->message = "手机号未绑定";
						return $result;
					}
			    break;
				
				case 'isBing':
					$strCode = "【安管控】您正在修改绑定手机号，请确认是否是本人操作，验证码：".$code.",有效期5分钟";
					$where = "phone = {$phone} and status=2 and id={$userId}";
					$emptyUserId = $userModel->selectOne($where, "id,phone,isBind");
					if(empty($emptyUserId['id'])){ $result->message = "该用户未找到或已被删除，请联系管理员修改"; return $result;}
					$insertData['userId'] = $userId;
					$result->data[] = ['userId'=>$userId, 'phone'=>$phone];
				break;
				# 该方法暂时废弃 原因：和重置密码冗余了
				/*case 'retrieve':
					$strCode = "【安管控】您正在找回密码，验证码：".$code.",有效期5分钟";
					$where = "phone = {$phone} and status =2 ";
					$emptyUserId = $userModel->selectOne($where, "id,phone,isBind");
					if(empty($emptyUserId['id']) || $emptyUserId['isBind']!=1){$result->message = "该手机号未绑定"; return $result;}
					$insertData['userId'] = $emptyUserId['id'];
					$result->data[] = ['userId'=>$emptyUserId['id'],'phone'=>$phone];
				break;*/
				  
				default:
					$result->message = "请选择正确的发送方式";
					return $result;
			}#end switch
			
			
			#插入接口
			$verifyModel->delete("phone={$phone}");
			$ret = $verifyModel->insert($insertData, true);
			if(!$ret){$result->message = "当前网络环境差发送验证码失败，请重新获取"; $result->data = []; return $result;}
			
			#短信接口
			$encryptObj = new MagicCrypt();
			$smsend = $encryptObj->SendSMSEnd($phone,$strCode);
            $result->message = $smsend->result;
            if($smsend->result!="SUCCESS"){$result->message = "当前网络环境差发送验证码失败，请重新获取"; $result->data = []; return $result;}
			
			$result->code = 200; 
			$result->message = "发送成功";
			
		}catch(Exception $e){
			$result->message = $e->getMessage();
		}
        return $result; 
	}
	
	//App绑定手机号 第一步：验证手机号是否本人
	public function isBingPhone(UserPhoneLogin $user){
		#接受参数
		$userId = $user->userid ? gdl_lib_BaseUtils::getStr($user->userid) : "";
		$phone = $user->phone ? gdl_lib_BaseUtils::getStr($user->phone) : "";
		$code = $user->code ? gdl_lib_BaseUtils::getStr($user->code) : "";
		
		#实例化返回
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($userId)){$result->message = "未找到绑定用户"; return $result;}
		if(empty($phone)){$result->message = "请填写手机号码"; return $result;}
		if(empty($code)){$result->message = "请输入6位验证码"; return $result;}
		
		$ret = self::checkCode($phone, $code, $userId);
		if(!$ret){$result->message = "验证码错误"; return $result;}
		
		#业务
		try{
			$userModel = new model_attendance_member();
			$verifyModel = new model_attendance_verifycode();
			#验证手机是否已经被绑定
			$where = "phone = {$phone} and status =2 and id = {$userId}";
			$emptyUserId = $userModel->selectOne($where, "id,phone,isBind");	
			if($emptyUserId['id']){
				#绑定成功删除数据库验证码
				$verifyModel->delete("phone={$phone}");
				$result->code = 200; 
				$result->message = "验证成功";
			}else{
				$result->message = "验证失败，请确认是本人操作";
			}
		} catch (Exception $e) {
            $result->success = true;
            $result->code = 0;
            $result->message = $e->getMessage();
        }
		 
        return $result; 
	}
	
	//App绑定手机号 第二步：绑定手机号
	public function bingPhone(UserPhoneLogin $user){
		#接受参数
		$userId = $user->userid ? gdl_lib_BaseUtils::getStr($user->userid) : "";
		$phone = $user->phone ? gdl_lib_BaseUtils::getStr($user->phone) : "";
		$code = $user->code ? gdl_lib_BaseUtils::getStr($user->code) : "";
		
		#实例化返回
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($userId)){$result->message = "未添加绑定用户"; return $result;}
		if(empty($phone)){$result->message = "请填写手机号码"; return $result;}
		if(empty($code)){$result->message = "请输入6位验证码"; return $result;}
		
		$ret = self::checkCode($phone, $code, $userId);
		if(!$ret){$result->message = "验证码错误"; return $result;}
		
		#业务
		try{
			$userModel = new model_attendance_member();
			$verifyModel = new model_attendance_verifycode();
			#验证手机是否已经被绑定
			$where = "phone = {$phone} and status =2 ";
			$emptyUserId = $userModel->selectOne($where, "id,phone,isBind");
			if($emptyUserId['phone'] && $emptyUserId['isBind']==1){$result->message = "该手机号已被注册，请勿重复绑定"; return $result;}
			
			$upDate = ['phone'=>$phone, 'isBind'=>1];
			
			$upWhere = "id={$userId}";
			$rets = $userModel->update($upWhere, $upDate);
			if($rets){
				#绑定成功删除数据库验证码
				$verifyModel->delete("phone={$phone}");
				$result->message = "绑定成功,下次可以使用手机号码加密码登录";
				$result->code = 200;
				$result->data[] = ['userId'=>$userId, 'phone'=>$phone ,'isBind'=>1];
			}else{
				$result->message = "该手机号已绑定，请勿重复绑定";
			}
		} catch (Exception $e) {
            $result->success = true;
            $result->code = 0;
            $result->message = $e->getMessage();
        }
		 
        return $result; 
	}
	//App发送短信手机号码登录
	public function userPhoneLogin(UserPhoneLogin $user){
		#接受参数
		$userId = $user->userid ? gdl_lib_BaseUtils::getStr($user->userid) : "";
		$phone = $user->phone ? gdl_lib_BaseUtils::getStr($user->phone) : "";
		$code = $user->code ? gdl_lib_BaseUtils::getStr($user->code) : "";
		 
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($userId)){$result->message = "缺少UserId"; return $result;}
		if(empty($phone)){$result->message = "请填写手机号码"; return $result;}
		if(empty($code)){$result->message = "请输入6位验证码"; return $result;}
		
		$ret = self::checkCode($phone, $code, $userId);
		if(!$ret){$result->message = "验证码错误"; return $result;}
		
		try{
			#查询该用户
			$userModel = new model_attendance_member();
			$verifyModel = new model_attendance_verifycode();
			$processService = new service_appprocess();# 获取审批流程规则
			$condition['phone'] = $phone;
			$condition['id'] = $userId;
			$condition['status'] = 2;
			$userFiled = "*";
			$user = $userModel->selectOne($condition, $userFiled);
			if(empty($user['id'])){$result->message = "该手机号码未绑定"; return $result;}
			$platformId = $user['platformId']?$user['platformId']:0;
			
			#修改操作 登录成功新增用户token和过期时间
			$token = parent::random(32); 
			$tokenTimeOut = time()+7200; 
			$updateUser = ['lastLoginTime'=>time(), 'token'=>$token, 'tokenTimeOut'=>$tokenTimeOut, 'isFirstLogin'=>2]; # isFirstLogin 1：第一次登陆 2：正常
			$upWhere['id'] = $user['id'];
			$addToken = $userModel->update($upWhere, $updateUser);
			
			#部门
			 $unitsModel = new model_lhbase_units();
			 $departmentId = isset($user['unitId'])?$user['unitId']:$user['departmentId'];
			 $unitsWhere = "id={$departmentId}";
			 $departmentName = $unitsModel->selectOne($unitsWhere, "id,unitName");
			 $departmentName = isset($departmentName['unitName'])?$departmentName['unitName']:"无部门";
			 
			 #职位
			 $positionModel = new model_attendance_position();
			 $positionId = isset($user['positionId'])?$user['positionId']:0;
			 $positionWhere = "id ={$positionId}";
			 $positionName = $positionModel->selectOne($positionWhere, "id,title");
			 $positionName = isset($positionName['title'])?$positionName['title']:"无职位";
			 
			 #性别
			 $sex = $this->checkSex($user['idcard']);
			 if(empty($user['idcard'])){$sex = 0;}
			 
			#考情组
			$kqModel = new model_attendance_attendancegroup();
			$leftJoin = [
				'atd_attendance_group_user as kquser' => 'atd_attendance_group.id=kquser.agId',
			];
			$kqFiled = "kquser.id,atd_attendance_group.id, atd_attendance_group.title";
			$kqWhere = "kquser.memberId={$user['id']} and atd_attendance_group.isdelete=0";
			$proInfo = $kqModel->selectOne($kqWhere,$kqFiled,'','',$leftJoin);
			$kqId = $proInfo['id']?$proInfo['id']:"0";
			$kqName = $proInfo['title']?$proInfo['title']:"无考勤组";
			
			#查请假流程
			$leave = 1; #1：有审批流程 2：没有
			$processResult = $processService->getMemberProcess($userId, $platformId, 1); #1:请假 2：外出 3：补卡 
			$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
			if(empty($recomdRule)){$leave = 2;}
			#外出流程
			$outgo = 1; #1：有审批流程 2：没有
			$processResult = $processService->getMemberProcess($userId, $platformId, 2); #1:请假 2：外出 3：补卡 
			$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
			if(empty($recomdRule)){$outgo = 2;}
			#补卡流程
			$recard = 1; #1：有审批流程 2：没有
			$processResult = $processService->getMemberProcess($userId, $platformId, 3); #1:请假 2：外出 3：补卡 
			$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
			if(empty($recomdRule)){$recard = 2;}
			
			if($addToken){
				#返回数据
				$photo = $user['photo']?$user['photo']:self::$photo;
				$resultData['userInfo'] = json_encode(['userId'=>$user['id'],'leave'=>$leave,'outgo'=>$outgo,'recard'=>$recard,'proGroupName'=>$kqName,'proGroupId'=>$kqId,'sex'=>$sex, 'isFirstLogin'=>$user['isFirstLogin'], 'departmentName'=>$departmentName, 'positionName'=>$positionName,'jobnumber'=>$user['jobnumber'], 'photo'=>$photo, 'photoStatus'=>$user['photoStatus'], 'platformId'=>$user['platformId'], 'unitId'=>$user['unitId'], 'userName'=>$user['userName'], 'realName'=>$user['realName'], 'idcard'=>$user['idcard'], 'phone'=>$user['phone'],'isBindPhone'=>$user['isBind'],'isCharge'=>$user['isCharge'],'token'=>$token]);
				
				#登录成功删除数据库验证码
				$verifyModel->delete("phone={$phone}");
				$result->data[] = $resultData;
				$result->code = 200;
				$result->message = "登录成功";
			}else{
				$result->message = "token更新失败";
			}
		}catch(Exception $e){
			$e->getMessage();
		}
        return $result; 
	}
	
	//短信验证码找回密码
	public function userForgetPassword(UserDTO $user){
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : "";
		
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($data['phone'])){$result->message = "请输入手机号"; return $result;}
		if(empty($data['userId'])){$result->message = "缺少UserID"; return $result;}
		if(empty($data['code'])){$result->message = "请输入6验证码"; return $result;}
		if(empty($data['password'])){$result->message = "请输入新密码"; return $result;}
		if(empty($data['rePassword'])){$result->message = "请重复输入新密码"; return $result;}
		if($data['password']!=$data['rePassword']){$result->message = "两次密码不一致"; return $result;}
		
		# 验证码验证
		$ret = self::checkCode($data['phone'], $data['code'], $data['userId']);
		if(!$ret){$result->message = "验证码错误"; return $result;}
		
		try{
			$userModel = new model_attendance_member();
			$verifyModel = new model_attendance_verifycode();
			$emptyWhere = "phone ={$data['phone']} and isBind=1 and status =2 and id={$data['userId']}";
			$emptyField = "id,phone,isBind";
			$emptyUserId = $userModel->selectOne($emptyWhere, $emptyUserId);
			if(empty($emptyUserId['id'])){$result->message = "该手机号码未绑定或已被删除，请联系管理员重新注册"; return $result;}
			
			$upData['passsalt'] = parent::random(8);
			$upData['password'] = parent::dpassword($data['password'], $upData['passsalt']);
			$upData['updateTime'] = time();
			$upWhere = "id={$data['userId']}";
			
			$r = $userModel->update($upWhere, $upData);
			if($r){
				#登录成功删除数据库验证码
				$verifyModel->delete("phone={$phone}");
				$result->code = 200;
				$result->message = "修改密码成功";
			}else{
				$result->code =200;
				$result->message = "您已修改密码，请勿重复修改";
			}
			
		}catch(Exception $e){
			$result->message = $e->getMessage();
		}
		return $result;
	}
	
	//照片采集上传
	public function userUploadPhoto(UserDTO $user){ 
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : "";
		
		$userId = $data['userId'];
		$url = $data['url'];
		
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($data['url'])){$result->message = "图片未上传"; return $result;}
		if(empty($data['userId'])){$result->message = "缺少userId"; return $result;}
		
		try{
			$userModel = new model_attendance_member();
			$upData = ['photoStatus'=>1, 'photo'=>$url];
			$upWhere = "id={$userId}";
			$ret = $userModel->update($upWhere, $upData);
			if($ret){
				$result->code = 200; 
				$result->message = "上传留底照片成功，等待审核";
				$result->data[] = ['userId'=>$userId, 'url'=>$url, 'photoStatus'=>1];
			}else{
				$result->message = "上传失败";
			}
			
		}catch(Exception $e){
			$result->message = $e->getMessage();
		}
		
		return $result;
	}
	
	//旧密码修改
	public function userRePassword(UserDTO $user){
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : "";
		
		#接受参数
		$oldPassword = $data['oldPassword']?$data['oldPassword']:"";
		$newPassword = $data['newPassword']?$data['newPassword']:"";
		$rePassword = $data['rePassword']?$data['rePassword']:"";
		$userId = $data['userId']?$data['userId']:"";
		
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($userId)){$result->message = "请选择需要修改密码的用户"; return $result;}
		if(empty($oldPassword)){$result->message = "请输入旧密码"; return $result;}
		if(empty($newPassword) || strlen($newPassword)<6){$result->message = "请输入6位以上的新密码"; return $result;}
		if(empty($rePassword) || strlen($rePassword)<6){$result->message = "请重复6位以上的新密"; return $result;}
		if($newPassword!=$rePassword){$result->message = "两次密码不一致"; return $result;}
		
		try{
			$userModel = new model_attendance_member();
			
			$emptyWhere = "status=2 and id={$userId}";
			$emptyUserId = $userModel->selectOne($emptyWhere, "id,passsalt,password");
			if(empty($emptyUserId['id'])){$result->message = "用户不存在或已被禁用"; return $result;}
			
			#旧密码
			$randPassword = md5((gdl_lib_BaseUtils::IsMd5($oldPassword) ? md5($oldPassword) : md5(md5($oldPassword))) . $emptyUserId['passsalt']);
			if($randPassword!=$emptyUserId['password']){$result->message = "修改失败，旧密码不正确";  return $result;}
			
			#插入新密码
			$upData['passsalt'] = parent::random(8);
			$upData['password'] = parent::dpassword($newPassword, $upData['passsalt']);
			$upWhere = "id={$userId}";
			$ret = $userModel->update($upWhere, $upData);
			if($ret){
				$result->message = "密码已修改，请重新登录";
				$result->code = 200;
			}else{
				$result->message = "修改失败，用户已被禁用，请联系管理开启";
			}
			
		}catch(Exception $e){
			$result->message = $e->getMessage();
		}
		
		return $result;
	}
	
	//App用户详情 往后有什么参数新增全部在此方法新增
	public function userInfo(UserDTO $user){
		#接受参数
		$data = $user->data ? gdl_lib_BaseUtils::getStr($user->data) : "";
		$userId = !empty($data['userId']) ? $data['userId'] : "";
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		#验证
		if(empty($userId)){$result->message = "用户不存在"; return $result;}
			
		try{
			$userModel = new model_attendance_member();
			$condition['status'] = 2;
			$condition['id'] = $userId;
			$userFiled = "*";
			$user = $userModel->selectOne($condition, $userFiled);
			$platformId = $user['platformId']?$user['platformId']:0;
			
			if($user['id']){  
				 #部门
				 $unitsModel = new model_lhbase_units();
				 $processService = new service_appprocess();# 获取审批流程规则
				 $departmentId = isset($user['unitId'])?$user['unitId']:$user['departmentId'];
				 $unitsWhere = "id={$departmentId}";
				 $departmentName = $unitsModel->selectOne($unitsWhere, "id,unitName");
				 $departmentName = isset($departmentName['unitName'])?$departmentName['unitName']:"无部门";
				 
				 #职位
				 $positionModel = new model_attendance_position();
				 $positionId = isset($user['positionId'])?$user['positionId']:0;
				 $positionWhere = "id ={$positionId}";
				 $positionName = $positionModel->selectOne($positionWhere, "id,title");
				 $positionName = isset($positionName['title'])?$positionName['title']:"无职位";
				 
				 #性别
				 $sex = $this->checkSex($user['idcard']);
				 if(empty($user['idcard'])){$sex = 0;}
				 #考情组
				$kqModel = new model_attendance_attendancegroup();
				$leftJoin = [
					'atd_attendance_group_user as kquser' => 'atd_attendance_group.id=kquser.agId',
				];
				$kqFiled = "kquser.id,atd_attendance_group.id, atd_attendance_group.title";
				$kqWhere = "kquser.memberId={$user['id']} and atd_attendance_group.isdelete=0";
				$proInfo = $kqModel->selectOne($kqWhere,$kqFiled,'','',$leftJoin);
				$kqId = $proInfo['id']?$proInfo['id']:"0";
				$kqName = $proInfo['title']?$proInfo['title']:"无考勤组";
				
				#查请假流程
				$leave = 1; #1：有审批流程 2：没有
				$processResult = $processService->getMemberProcess($userId, $platformId, 1); #1:请假 2：外出 3：补卡 
				$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
				if(empty($recomdRule)){$leave = 2;}
				#外出流程
				$outgo = 1; #1：有审批流程 2：没有
				$processResult = $processService->getMemberProcess($userId, $platformId, 2); #1:请假 2：外出 3：补卡 
				$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
				if(empty($recomdRule)){$outgo = 2;}
				#补卡流程
				$recard = 1; #1：有审批流程 2：没有
				$processResult = $processService->getMemberProcess($userId, $platformId, 3); #1:请假 2：外出 3：补卡 
				$recomdRule = $processService->actionApprocess($userId, $processResult['rules']);
				if(empty($recomdRule)){$recard = 2;}
				
				#返回数据
				$photo = $user['photo']?$user['photo']:self::$photo;
				$resultData['userInfo'] = json_encode(['userId'=>$user['id'],'leave'=>$leave,'outgo'=>$outgo,'recard'=>$recard,'proGroupName'=>$kqName,'proGroupId'=>$kqId,'sex'=>$sex, 'photoInfo'=>$user['photoInfo'],'isFirstLogin'=>$user['isFirstLogin'], 'departmentName'=>$departmentName, 'positionName'=>$positionName,'jobnumber'=>$user['jobNumber'], 'photo'=>$photo, 'photoStatus'=>$user['photoStatus'], 'platformId'=>$user['platformId'], 'unitId'=>$user['unitId'], 'userName'=>$user['userName'], 'realName'=>$user['realName'], 'idcard'=>$user['idcard'], 'phone'=>$user['phone'],'isBindPhone'=>$user['isBind'],'isCharge'=>$user['isCharge']]);
				$result->data[] = $resultData;
				$result->code = 200;
				$result->message = "获取成功";				 
			}else{
				$result->message = "用户不存在或已被删除，请联系管理员添加"; 
			}
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		 
        return $result; 
	}
	
	//判断验证码
	public function checkCode($phone, $code, $userId){
		# 查询验证码数据是否有该验证码
		$where = " status =1 and phone ={$phone} ";
		if($userId){
			$where.= " and userId={$userId}"; 
		}
		$usercode = new model_attendance_verifycode();
		$usercodeEnd = $usercode->selectOne($where,'code,expireTime,phone'); 
		if(empty($usercodeEnd['code'])){
			//return '验证失败，验证码不存在';
			return false;
		} else {
			if($usercodeEnd['code']!=$code){ 
				//return '验证码错误';
				return false;
			}
			if($usercodeEnd['expireTime']<time()){ 
				//return '验证码,已过期';
				return false;
			}
		}
		return true;
	}
	
	//根据身份证判断性别
	public function checkSex($idcard) {
		//根据身份证号，自动返回性别 1女 2男
		if(empty($idcard)) return 2;
		$sexint = (int)substr($idcard,16,1);
		return $sexint % 2 === 0 ? 1 : 2;
	}
	 
}

